<template>
  <div class="suggestion-page" style="padding: 20px;">
    <!-- 筛选栏 -->
    <div class="filter-bar" style="display: flex; gap: 10px; margin-bottom: 16px;">
      <el-select v-model="filterRegion" placeholder="区域筛选" size="small" clearable>
        <el-option v-for="item in uniqueRegions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="filterDevice" placeholder="设备筛选" size="small" clearable>
        <el-option v-for="item in uniqueDevices" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="filterLevel" placeholder="优先级" size="small" clearable>
        <el-option label="高" value="高" />
        <el-option label="中" value="中" />
        <el-option label="低" value="低" />
      </el-select>
      <el-input v-model="search" placeholder="关键词搜索(问题/建议)" size="small" clearable style="width: 200px;" />
      <el-button size="small" type="info" plain @click="toggleIgnored">
        {{ showIgnored ? '隐藏已忽略' : '查看已忽略' }}
      </el-button>
      <el-button size="small" type="success" plain @click="toggleAccepted">
        {{ showAccepted ? '隐藏已采纳' : '查看已采纳' }}
      </el-button>
    </div>

    <!-- 未处理建议 -->
    <el-row :gutter="20" v-if="!showIgnored && !showAccepted">
      <el-col :span="12" v-for="(item, index) in filteredList" :key="index">
        <el-card shadow="hover" style="margin-bottom: 20px;">
          <template #header>
            <div style="display: flex; justify-content: space-between;">
              <div>
                <strong style="color: #67C23A;">{{ item.region }}</strong>
                <span style="margin-left: 10px;">🔧 {{ item.device }}</span>
                <el-tag :type="levelTag(item.level)" size="small" style="margin-left: 10px">{{ item.level }}优先</el-tag>
              </div>
              <el-button text type="primary" @click="item.expanded = !item.expanded">
                {{ item.expanded ? '收起' : '详情' }}
              </el-button>
            </div>
          </template>

          <div>
            <div><strong>问题：</strong>{{ item.issue }}</div>
            <div><strong>建议：</strong>{{ item.suggestion }}</div>
            <el-collapse-transition>
              <div v-if="item.expanded" style="margin-top: 10px; font-size: 13px; color: #666;">
                <div><strong>发现时间：</strong>{{ item.timestamp }}</div>
                <div><strong>相关数据：</strong>{{ item.data }}</div>
                <div><strong>历史建议：</strong>
                  <ul>
                    <li v-for="(h, i) in item.history" :key="i">{{ h }}</li>
                  </ul>
                </div>
              </div>
            </el-collapse-transition>
            <div style="display: flex; justify-content: flex-end; gap: 6px; margin-top: 12px;">
              <el-button size="small" type="primary" @click="accept(item)">采纳</el-button>
              <el-button size="small" type="danger" plain @click="ignore(item)">忽略</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 已忽略 -->
    <el-row :gutter="20" v-if="showIgnored">
      <el-col :span="12" v-for="(item, index) in ignoredList" :key="index">
        <el-card shadow="never" style="margin-bottom: 12px;">
          <div style="display: flex; justify-content: space-between;">
            <div>
              <strong>{{ item.region }} ▏{{ item.device }}</strong>
              <div style="font-size: 13px; margin-top: 6px;"><strong>问题：</strong>{{ item.issue }}</div>
              <div style="font-size: 13px;"><strong>建议：</strong>{{ item.suggestion }}</div>
            </div>
            <el-button size="small" type="success" plain @click="restore(item)">恢复</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 已采纳 -->
    <el-row :gutter="20" v-if="showAccepted">
      <el-col :span="12" v-for="(item, index) in acceptedList" :key="index">
        <el-card shadow="hover" style="margin-bottom: 20px;">
          <template #header>
            <div style="display: flex; justify-content: space-between;">
              <div>
                <strong style="color: #409EFF;">{{ item.region }}</strong>
                <span style="margin-left: 10px;">✅ {{ item.device }}</span>
                <el-tag :type="levelTag(item.level)" size="small" style="margin-left: 10px">{{ item.level }}优先</el-tag>
              </div>
              <el-tag size="small" type="success">已采纳</el-tag>
            </div>
          </template>
          <div>
            <div><strong>问题：</strong>{{ item.issue }}</div>
            <div><strong>建议：</strong>{{ item.suggestion }}</div>
            <div style="margin-top: 10px; font-size: 13px; color: #666;">
              <div><strong>发现时间：</strong>{{ item.timestamp }}</div>
              <div><strong>相关数据：</strong>{{ item.data }}</div>
              <div><strong>历史建议：</strong>
                <ul>
                  <li v-for="(h, i) in item.history" :key="i">{{ h }}</li>
                </ul>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()

const showIgnored = ref(false)
const showAccepted = ref(false)

const allSuggestions = ref([
  { region: 'A栋', device: '插座', level: '中', issue: '夜间仍供电', suggestion: '设定深夜自动断电', expanded: false, timestamp: '2024-04-03 00:10', data: '插座功耗 > 5kWh', history: [] },
  { region: 'B栋', device: '饮水机', level: '低', issue: '无人使用仍运行', suggestion: '人感联动断电', expanded: false, timestamp: '2024-04-02 15:30', data: '连续 3 小时无操作', history: ['2024-03-18 已提示节能运行'] },
  { region: 'C栋', device: '电梯', level: '高', issue: '空载运行频繁', suggestion: '低峰待机', expanded: false, timestamp: '2024-04-03 08:50', data: '0 乘客运行率 > 60%', history: [] },
  { region: 'B栋', device: '加湿器', level: '中', issue: '湿度已达标仍持续工作', suggestion: '设置湿度阈值', expanded: false, timestamp: '2024-04-03 09:30', data: '湿度 > 70%', history: [] },
  { region: 'C栋', device: '锅炉', level: '高', issue: '夜间功耗高', suggestion: '设置夜间自动降压', expanded: false, timestamp: '2024-04-03 03:00', data: '持续运行超 6 小时', history: ['2024-02-01 建议热水器联动控制'] },
  { region: 'A栋', device: '空调', level: '高', issue: '频繁启停', suggestion: '启用变频', expanded: false, timestamp: '2024-04-01 09:22', data: '启停次数 > 30 次/天', history: ['2024-03-01 建议设置定时器'] },
  { region: 'B栋', device: '照明', level: '中', issue: '白天仍开灯', suggestion: '增加光感开关', expanded: false, timestamp: '2024-04-02 11:10', data: '光照 > 800 Lux', history: [] },
  { region: 'C栋', device: '新风系统', level: '高', issue: '夜间负载高', suggestion: '低负荷关机', expanded: false, timestamp: '2024-04-01 22:40', data: '风机负载 90%', history: [] }
])

const ignoredList = ref([])
const acceptedList = ref([])

const filterRegion = ref('')
const filterDevice = ref('')
const filterLevel = ref('')
const search = ref('')

const toggleIgnored = () => {
  showIgnored.value = !showIgnored.value
  showAccepted.value = false
}
const toggleAccepted = () => {
  showAccepted.value = !showAccepted.value
  showIgnored.value = false
}

const uniqueDevices = computed(() => [...new Set(allSuggestions.value.map(i => i.device).filter(Boolean))])
const uniqueRegions = computed(() => [...new Set(allSuggestions.value.map(i => i.region).filter(Boolean))])
const levelWeight = { 高: 3, 中: 2, 低: 1 }

const filteredList = computed(() =>
  allSuggestions.value
    .filter(item =>
      (!filterRegion.value || item.region === filterRegion.value) &&
      (!filterDevice.value || item.device === filterDevice.value) &&
      (!filterLevel.value || item.level === filterLevel.value) &&
      (!search.value || item.issue.includes(search.value) || item.suggestion.includes(search.value))
    )
    .sort((a, b) => levelWeight[b.level] - levelWeight[a.level])
)

function levelTag(level) {
  return level === '高' ? 'danger' : level === '中' ? 'warning' : 'success'
}

function ignore(item) {
  const i = allSuggestions.value.indexOf(item)
  if (i !== -1) {
    ignoredList.value.push(item)
    allSuggestions.value.splice(i, 1)
    ElMessage.warning(`已忽略：${item.device} - ${item.region}`)
  }
}

function restore(item) {
  ignoredList.value = ignoredList.value.filter(x => x !== item)
  allSuggestions.value.push(item)
  ElMessage.success(`已恢复：${item.device}`)
}

function accept(item) {
  const i = allSuggestions.value.indexOf(item)
  if (i !== -1) {
    acceptedList.value.push(item)
    allSuggestions.value.splice(i, 1)
  }
  router.push({
    path: '/decision/plan',
    query: {
      energy: guessEnergy(item.device),
      device: item.device,
      note: item.suggestion,
      auto: 'true'
    }
  })
  ElMessage.success('已采纳并跳转生成策略')
}

function guessEnergy(device) {
  if (device.includes('空调') || device.includes('照明') || device.includes('电梯') || device.includes('插座')) return '电'
  if (device.includes('加湿器') || device.includes('饮水机') || device.includes('洗手间')) return '水'
  if (device.includes('锅炉') || device.includes('燃气') || device.includes('热水器')) return '气'
  return '电'
}
</script>

<style scoped>
.suggestion-page {
  max-width: 1200px;
  margin: 0 auto;
}
</style>